//! 协议兼容性测试

use std::collections::HashMap;
use std::sync::Arc;
use tokio::time::{sleep, Duration};
use serde_json::json;

use nacos_server::server::{NacosServer, ServerConfig};
use nacos_cluster::ClusterConfig;
use nacos_naming::NamingConfig;
use nacos_config::ConfigConfig;
use nacos_network::NetworkConfig;

/// 测试REST API协议兼容性
#[tokio::test]
async fn test_rest_api_compatibility() {
    let config = ServerConfig {
        port: 8850,
        ip: "127.0.0.1".to_string(),
        cluster: ClusterConfig::default(),
        naming: NamingConfig::default(),
        config: ConfigConfig::default(),
        network: NetworkConfig::default(),
        tls_enabled: false,
        max_connections: 100,
        request_timeout: 5000,
    };

    let server = NacosServer::new(config).unwrap();
    
    // 启动服务器
    server.start().await.unwrap();
    
    // 等待服务器启动
    sleep(Duration::from_secs(2)).await;
    
    // 测试健康检查端点
    let client = reqwest::Client::new();
    let response = client
        .get("http://127.0.0.1:8850/health")
        .send()
        .await
        .unwrap();
    
    assert_eq!(response.status(), 200);
    let body: serde_json::Value = response.json().await.unwrap();
    assert_eq!(body["code"], 200);
    
    // 测试命名服务API
    let response = client
        .post("http://127.0.0.1:8850/nacos/v1/ns/instance")
        .json(&json!({
            "namespace": "test-ns",
            "service_name": "test-service",
            "ip": "127.0.0.1",
            "port": 8080,
            "weight": 1.0,
            "healthy": true,
            "enabled": true,
            "ephemeral": true
        }))
        .send()
        .await
        .unwrap();
    
    assert_eq!(response.status(), 200);
    
    // 测试配置服务API
    let response = client
        .post("http://127.0.0.1:8850/nacos/v1/cs/configs")
        .json(&json!({
            "namespace": "test-ns",
            "group": "test-group",
            "data_id": "test-data",
            "content": "test-content"
        }))
        .send()
        .await
        .unwrap();
    
    assert_eq!(response.status(), 200);
    
    // 停止服务器
    server.stop().await.unwrap();
}

/// 测试gRPC API协议兼容性
#[tokio::test]
async fn test_grpc_api_compatibility() {
    let config = ServerConfig {
        port: 8851,
        ip: "127.0.0.1".to_string(),
        cluster: ClusterConfig::default(),
        naming: NamingConfig::default(),
        config: ConfigConfig::default(),
        network: NetworkConfig::default(),
        tls_enabled: false,
        max_connections: 100,
        request_timeout: 5000,
    };

    let server = NacosServer::new(config).unwrap();
    
    // 启动服务器
    server.start().await.unwrap();
    
    // 等待服务器启动
    sleep(Duration::from_secs(2)).await;
    
    // 测试gRPC连接
    let channel = tonic::transport::Channel::from_static("http://127.0.0.1:9090")
        .connect()
        .await;
    
    assert!(channel.is_ok());
    
    // 停止服务器
    server.stop().await.unwrap();
}

/// 测试集群协议兼容性
#[tokio::test]
async fn test_cluster_protocol_compatibility() {
    use nacos_network::grpc::client::ClusterClient;
    use nacos_network::grpc::proto::RegisterInstanceRequest;
    
    let config1 = ServerConfig {
        port: 8852,
        ip: "127.0.0.1".to_string(),
        cluster: ClusterConfig {
            cluster_id: "test-cluster".to_string(),
            node_id: "node1".to_string(),
            listen_addr: "127.0.0.1:8852".to_string(),
            peers: vec!["127.0.0.1:8853".to_string()],
            election_timeout: 3000,
            heartbeat_interval: 1000,
            max_election_timeout: 5000,
        },
        ..Default::default()
    };

    let config2 = ServerConfig {
        port: 8853,
        ip: "127.0.0.1".to_string(),
        cluster: ClusterConfig {
            cluster_id: "test-cluster".to_string(),
            node_id: "node2".to_string(),
            listen_addr: "127.0.0.1:8853".to_string(),
            peers: vec!["127.0.0.1:8852".to_string()],
            election_timeout: 3000,
            heartbeat_interval: 1000,
            max_election_timeout: 5000,
        },
        ..Default::default()
    };

    let server1 = NacosServer::new(config1).unwrap();
    let server2 = NacosServer::new(config2).unwrap();
    
    // 启动两个服务器
    server1.start().await.unwrap();
    server2.start().await.unwrap();
    
    // 等待集群形成
    sleep(Duration::from_secs(5)).await;
    
    // 测试集群通信
    let status1 = server1.get_cluster_integration().get_cluster_status().await.unwrap();
    let status2 = server2.get_cluster_integration().get_cluster_status().await.unwrap();
    
    assert_eq!(status1.cluster_id, "test-cluster");
    assert_eq!(status2.cluster_id, "test-cluster");
    assert!(status1.total_nodes >= 1);
    assert!(status2.total_nodes >= 1);
    
    // 停止服务器
    server1.stop().await.unwrap();
    server2.stop().await.unwrap();
}

/// 测试数据同步协议
#[tokio::test]
async fn test_data_sync_protocol() {
    use nacos_network::grpc::client::DataSyncClient;
    use nacos_network::grpc::proto::SyncMessage;
    
    let config = ServerConfig {
        port: 8854,
        ip: "127.0.0.1".to_string(),
        cluster: ClusterConfig::default(),
        naming: NamingConfig::default(),
        config: ConfigConfig::default(),
        network: NetworkConfig::default(),
        tls_enabled: false,
        max_connections: 100,
        request_timeout: 5000,
    };

    let server = NacosServer::new(config).unwrap();
    
    // 启动服务器
    server.start().await.unwrap();
    
    // 等待服务器启动
    sleep(Duration::from_secs(2)).await;
    
    // 测试数据同步
    let sync_result = server.get_cluster_integration()
        .sync_data_to_cluster("test", "test-data")
        .await;
    
    assert!(sync_result.is_ok());
    
    // 停止服务器
    server.stop().await.unwrap();
}

/// 测试多协议并发访问
#[tokio::test]
async fn test_multi_protocol_concurrent_access() {
    let config = ServerConfig {
        port: 8855,
        ip: "127.0.0.1".to_string(),
        cluster: ClusterConfig::default(),
        naming: NamingConfig::default(),
        config: ConfigConfig::default(),
        network: NetworkConfig::default(),
        tls_enabled: false,
        max_connections: 100,
        request_timeout: 5000,
    };

    let server = NacosServer::new(config).unwrap();
    
    // 启动服务器
    server.start().await.unwrap();
    
    // 等待服务器启动
    sleep(Duration::from_secs(2)).await;
    
    let client = reqwest::Client::new();
    
    // 并发REST请求
    let mut handles = vec![];
    for i in 0..10 {
        let client = client.clone();
        let handle = tokio::spawn(async move {
            let response = client
                .post("http://127.0.0.1:8855/nacos/v1/ns/instance")
                .json(&json!({
                    "namespace": "test-ns",
                    "service_name": format!("test-service-{}", i),
                    "ip": "127.0.0.1",
                    "port": 8080 + i,
                    "weight": 1.0,
                    "healthy": true,
                    "enabled": true,
                    "ephemeral": true
                }))
                .send()
                .await;
            
            assert!(response.is_ok());
            assert_eq!(response.unwrap().status(), 200);
        });
        handles.push(handle);
    }
    
    // 等待所有请求完成
    for handle in handles {
        handle.await.unwrap();
    }
    
    // 停止服务器
    server.stop().await.unwrap();
}

/// 测试错误处理
#[tokio::test]
async fn test_error_handling() {
    let config = ServerConfig {
        port: 8856,
        ip: "127.0.0.1".to_string(),
        cluster: ClusterConfig::default(),
        naming: NamingConfig::default(),
        config: ConfigConfig::default(),
        network: NetworkConfig::default(),
        tls_enabled: false,
        max_connections: 100,
        request_timeout: 5000,
    };

    let server = NacosServer::new(config).unwrap();
    
    // 启动服务器
    server.start().await.unwrap();
    
    // 等待服务器启动
    sleep(Duration::from_secs(2)).await;
    
    let client = reqwest::Client::new();
    
    // 测试无效请求
    let response = client
        .post("http://127.0.0.1:8856/nacos/v1/ns/instance")
        .json(&json!({
            "invalid": "data"
        }))
        .send()
        .await
        .unwrap();
    
    assert!(response.status().is_client_error() || response.status().is_server_error());
    
    // 停止服务器
    server.stop().await.unwrap();
}

/// 测试性能基准
#[tokio::test]
async fn test_performance_benchmark() {
    let config = ServerConfig {
        port: 8857,
        ip: "127.0.0.1".to_string(),
        cluster: ClusterConfig::default(),
        naming: NamingConfig::default(),
        config: ConfigConfig::default(),
        network: NetworkConfig::default(),
        tls_enabled: false,
        max_connections: 1000,
        request_timeout: 5000,
    };

    let server = NacosServer::new(config).unwrap();
    
    // 启动服务器
    server.start().await.unwrap();
    
    // 等待服务器启动
    sleep(Duration::from_secs(2)).await;
    
    let client = reqwest::Client::new();
    let start_time = std::time::Instant::now();
    
    // 发送100个并发请求
    let mut handles = vec![];
    for i in 0..100 {
        let client = client.clone();
        let handle = tokio::spawn(async move {
            let response = client
                .post("http://127.0.0.1:8857/nacos/v1/ns/instance")
                .json(&json!({
                    "namespace": "test-ns",
                    "service_name": format!("test-service-{}", i),
                    "ip": "127.0.0.1",
                    "port": 8080 + i,
                    "weight": 1.0,
                    "healthy": true,
                    "enabled": true,
                    "ephemeral": true
                }))
                .send()
                .await;
            
            response.is_ok()
        });
        handles.push(handle);
    }
    
    // 等待所有请求完成
    let mut success_count = 0;
    for handle in handles {
        if handle.await.unwrap() {
            success_count += 1;
        }
    }
    
    let duration = start_time.elapsed();
    
    println!("Performance test: {} requests in {:?}", success_count, duration);
    assert!(success_count >= 95); // 95% success rate
    
    // 停止服务器
    server.stop().await.unwrap();
}

/// 测试长连接稳定性
#[tokio::test]
async fn test_long_connection_stability() {
    let config = ServerConfig {
        port: 8858,
        ip: "127.0.0.1".to_string(),
        cluster: ClusterConfig::default(),
        naming: NamingConfig::default(),
        config: ConfigConfig::default(),
        network: NetworkConfig::default(),
        tls_enabled: false,
        max_connections: 100,
        request_timeout: 5000,
    };

    let server = NacosServer::new(config).unwrap();
    
    // 启动服务器
    server.start().await.unwrap();
    
    // 等待服务器启动
    sleep(Duration::from_secs(2)).await;
    
    let client = reqwest::Client::new();
    
    // 持续10秒的请求
    let start_time = std::time::Instant::now();
    let mut request_count = 0;
    
    while start_time.elapsed() < Duration::from_secs(10) {
        let response = client
            .get("http://127.0.0.1:8858/health")
            .send()
            .await;
        
        if response.is_ok() && response.unwrap().status() == 200 {
            request_count += 1;
        }
        
        sleep(Duration::from_millis(100)).await;
    }
    
    println!("Long connection test: {} requests in 10 seconds", request_count);
    assert!(request_count >= 50); // 至少50个成功请求
    
    // 停止服务器
    server.stop().await.unwrap();
}

/// 测试负载均衡
#[tokio::test]
async fn test_load_balancing() {
    let config = ServerConfig {
        port: 8859,
        ip: "127.0.0.1".to_string(),
        cluster: ClusterConfig::default(),
        naming: NamingConfig::default(),
        config: ConfigConfig::default(),
        network: NetworkConfig::default(),
        tls_enabled: false,
        max_connections: 50,
        request_timeout: 5000,
    };

    let server = NacosServer::new(config).unwrap();
    
    // 启动服务器
    server.start().await.unwrap();
    
    // 等待服务器启动
    sleep(Duration::from_secs(2)).await;
    
    let client = reqwest::Client::new();
    
    // 测试负载均衡
    let mut handles = vec![];
    for i in 0..20 {
        let client = client.clone();
        let handle = tokio::spawn(async move {
            let response = client
                .get("http://127.0.0.1:8859/nacos/v1/cluster/status")
                .send()
                .await;
            
            response
        });
        handles.push(handle);
    }
    
    // 确保所有请求都能成功处理
    for handle in handles {
        let response = handle.await.unwrap();
        assert!(response.is_ok());
        assert_eq!(response.unwrap().status(), 200);
    }
    
    // 停止服务器
    server.stop().await.unwrap();
}

/// 测试内存使用
#[tokio::test]
async fn test_memory_usage() {
    let config = ServerConfig {
        port: 8860,
        ip: "127.0.0.1".to_string(),
        cluster: ClusterConfig::default(),
        naming: NamingConfig::default(),
        config: ConfigConfig::default(),
        network: NetworkConfig::default(),
        tls_enabled: false,
        max_connections: 100,
        request_timeout: 5000,
    };

    let server = NacosServer::new(config).unwrap();
    
    // 启动服务器
    server.start().await.unwrap();
    
    // 等待服务器启动
    sleep(Duration::from_secs(2)).await;
    
    let client = reqwest::Client::new();
    
    // 大量数据测试内存使用
    for i in 0..1000 {
        let response = client
            .post("http://127.0.0.1:8860/nacos/v1/ns/instance")
            .json(&json!({
                "namespace": "test-ns",
                "service_name": format!("test-service-{}", i),
                "ip": "127.0.0.1",
                "port": 8080 + i,
                "weight": 1.0,
                "healthy": true,
                "enabled": true,
                "ephemeral": true
            }))
            .send()
            .await;
        
        assert!(response.is_ok());
    }
    
    // 等待垃圾回收
    sleep(Duration::from_secs(1)).await;
    
    // 停止服务器
    server.stop().await.unwrap();
}